package cn.tedu.baidashi.service.Impl;

import cn.tedu.baidashi.exception.ServiceException;
import cn.tedu.baidashi.mapper.UserMapper;
import cn.tedu.baidashi.mapper.UserRoleMapper;
import cn.tedu.baidashi.model.User;
import cn.tedu.baidashi.model.UserRole;
import cn.tedu.baidashi.service.IUserService;
import cn.tedu.baidashi.vo.RegisterVO;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.crypto.bcrypt.BCryptPasswordEncoder;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;

/**
 * <p>
 *  服务实现类
 * </p>
 *
 * @author YYL
 * @since 2022-02-19
 */
@Service
public class UserServiceImpl extends ServiceImpl<UserMapper, User> implements IUserService {

    @Autowired
    private UserMapper userMapper;

    @Autowired
    private UserRoleMapper userRoleMapper;

    @Override
    @Transactional
    public void registerGuest(RegisterVO registerVO) {
        User user = userMapper.findUserByUsername(registerVO.getUsername());
        if(user!=null){
            throw new ServiceException("手机号已经被注册!");
        }
        //加密密码
        PasswordEncoder encoder = new BCryptPasswordEncoder();
        String pwd ="{bcrypt}"+ encoder.encode(registerVO.getPassword());

        User guest = new User()
                .setUsername(registerVO.getUsername())
                .setNickname(registerVO.getNickname())
                .setPassword(pwd)
                .setCreatetime(LocalDateTime.now())
                .setEnabled(1)
                .setLocked(0);

        int num = userMapper.insert(guest);
        if(num!=1){
            throw new ServiceException("数据库忙!");
        }

        UserRole userRole = new UserRole()
                .setRoleId(2)
                .setUserId(guest.getId());
        num = userRoleMapper.insert(userRole);
        if(num!=1){
            throw new ServiceException("数据库忙!");
        }

    }

    /**
     * 根据用户名查询用户
     * @param username
     * @return
     */
    @Override
    public User getUser(String username) {
        User user = userMapper.findUserByUsername(username);
        return user;
    }
}
